package cn.xz.tipsum.dialog

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.CountDownTimer
import android.view.Gravity
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import cn.xz.tipsum.utils.MD5Utils
import cn.xz.tipsum.R
import cn.xz.tipsum.base.BaseApplication
import cn.xz.tipsum.base.BaseDialogRxFragment
import cn.xz.tipsum.utils.AppHelper


/**
 * 应用过期弹窗
 * */
class LoseAppDialog: BaseDialogRxFragment() {

    private var mClickListener: OnClickListener? = null

    private var tvC: TextView? = null
    private var tvSure: TextView? = null
    private var ivTitle: ImageView? = null

    companion object {
        fun newInstance(
            mClickListener: OnClickListener
        ): LoseAppDialog {
            val mDialog = LoseAppDialog()
            mDialog.mClickListener = mClickListener
            return mDialog
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.dialog_app_lose
    }

    override fun configDialog() {
        this.setDialogSize(gravity = Gravity.CENTER,width = 350)
    }

    override fun initViews() {

        dialog?.let {
            tvC = it.findViewById(R.id.tv_c)
            tvSure = it.findViewById(R.id.tv_sure)
            ivTitle = it.findViewById(R.id.iv_title)
        }

        //点击外部不隐藏
        dialog?.setCancelable(false)
        dialog?.setCanceledOnTouchOutside(false)
        //视图
        initUI()

        ivTitle?.setOnClickListener {
            val clipboard: ClipboardManager = BaseApplication.getContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            clipboard.setPrimaryClip(ClipData.newPlainText(null,
                MD5Utils.getMD5(AppHelper.getUUID())
            ))
            Toast.makeText(BaseApplication.getContext(),"复制成功，请发送给客服吧~", Toast.LENGTH_LONG).show()
        }
    }

    private fun initUI(){
        val countDownTimer: CountDownTimer = object : CountDownTimer(8000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                //  每刷新一次都走一次这里
                tvSure?.post {
                    tvSure?.text = "${millisUntilFinished/1000}s后关闭本APP"
                }
            }

            override fun onFinish() {
                mClickListener?.onF()
            }
        }
        countDownTimer.start() //开启刷新
    }

    interface OnClickListener {
        fun onF()
    }
}